using System.Collections.Generic;
using Core;
using UnityEngine;

namespace g_gongjianta
{
    public class MonsterMainComponent : UnitComponent<Monster>, IUpdate
    {
        private readonly List<Wall> walls = new();

        public bool IsDead { get; private set; }

        public override void Awake()
        {
            base.Awake();

            IsDead = false;

            walls.Clear();
            var units = G.Unit().GetUnits<Wall>();
            foreach (var unit in units)
            {
                if (unit == null || unit.IsDisposed) continue;
                walls.Add(unit as Wall);
            }
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();
        }

        public void Update()
        {
            if (IsDisposed) return;
            if (IsDead)
            {
                Unit.Dispose();
                return;
            }

            for (var i = walls.Count - 1; i >= 0; i--)
            {
                var wall = walls[i];
                if (wall == null || wall.IsDisposed)
                {
                    walls.RemoveAt(i);
                }
            }

            Unit.Data.MoveDir = Vector2.left;

            foreach (var wall in walls)
            {
                var diff = wall.Pos - Unit.Pos;
                if (Mathf.Abs(diff.x) < Unit.Conf.AttackRange)
                {
                    Unit.Data.MoveDir = Vector2.zero;
                    break;
                }
            }
        }

        public void OnHurt()
        {
            IsDead = true;
        }
    }
}